package com.lagou.proxy;

import com.lagou.dao.AccountDao;
import com.lagou.dao.impl.JdbcAccountDaoImpl;
import com.lagou.factory.ProxyFactory;
import com.lagou.pojo.Account;
import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * <pre>
 * 描述：TODO
 * </pre>
 *
 * @类名：com.lagou.proxy.JdkProxy
 * @作者 mengwei
 * 创建日期：2020/10/15 10:49
 */
public class JdkProxy {

    public static void main(String[] args) throws Exception {
        AccountDao jdbcAccountDao = new JdbcAccountDaoImpl();
//        Class<?> proxyClass = Proxy.getProxyClass(jdbcAccountDao.getClass().getClassLoader(), jdbcAccountDao.getClass().getInterfaces());
        AccountDao proxyInstance = (AccountDao) Proxy.newProxyInstance(jdbcAccountDao.getClass().getClassLoader(), jdbcAccountDao.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("before");
                Object invoke = method.invoke(jdbcAccountDao, args);
                System.out.println("after");

                return invoke;
            }
        });

        Account account = proxyInstance.queryAccountByCardNo("6029621011000");
        System.out.println(account);

    }

    @Test
    public void factoryTest() throws Exception {
        AccountDao jdbcAccountDao = new JdbcAccountDaoImpl();

        AccountDao jdkProxy = ProxyFactory.newInstance().getJdkProxy(jdbcAccountDao);

        Account account = jdkProxy.queryAccountByCardNo("6029621011000");
        System.out.println(account);

    }
}
